package io.renren.modules.generator.controller;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import io.renren.common.utils.ValidateFileTypeUtil;
import io.renren.common.utils.excel.ExcelUtils;
import io.renren.modules.generator.entity.CustomerEntity;
import io.renren.modules.generator.export.CustomerExcelDataCreaterImpl;
import io.renren.modules.generator.service.CustomerService;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;



/**
 * 
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2018-11-27 10:21:22
 */
@RestController
@RequestMapping("generator/customer")
public class CustomerController {
    @Autowired
    private CustomerService customerService;

    @Autowired
    private ExcelUtils excelUtils;

    @Autowired
    private CustomerExcelDataCreaterImpl customerExcelDataCreater;


    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("generator:customer:list")
    public R list(@RequestParam Map<String, Object> params){

        Query query = new Query(params);

        List<CustomerEntity> list = customerService.queryPage(query);

        int total =customerService.queryPageTotal(params);

        PageUtils pageUtils = new PageUtils(list, total, query.getLimit(), query.getCurrPage());

        return R.ok().put("page", pageUtils);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id){
			CustomerEntity customer = customerService.info(id);

        return R.ok().put("customer", customer);
    }

    /**
     * 保存
     */
    @CacheEvict(value = "customerController:queryEntity",allEntries=true)
    @RequestMapping("/save")
    @RequiresPermissions("generator:customer:save")
    public R save(@RequestBody CustomerEntity customer){
			customerService.save(customer);

        return R.ok();
    }

    /**
     * 修改
     */
    @CacheEvict(value = {"customerController:queryEntity"},allEntries=true)
    @RequestMapping("/update")
    @RequiresPermissions("generator:customer:update")
    public R update(@RequestBody CustomerEntity customer){
        customerService.update(customer);
        return R.ok();
    }

    /**
     * 删除
     */
    @CacheEvict(value = "customerController:queryEntity",allEntries=true)
    @RequestMapping("/delete")
    @RequiresPermissions("generator:customer:delete")
    public R delete(@RequestBody Integer[] ids){

        customerService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 更新状态
     * @param ids
     * @return
     */
    @CacheEvict(value = "customerController:queryEntity",allEntries=true)
    @RequestMapping("/updateStatusByIds")
    @RequiresPermissions("generator:customer:status")
    public R updateStatusByIds(@RequestBody Integer[] ids){
        customerService.updateStatusByIds(Arrays.asList(ids));
        return R.ok();
    }

    @Cacheable(value = "customerController:queryEntity")
    @PostMapping("/queryEntity")
    public R queryEntity(@RequestBody Map<String,Object> params){
        List<CustomerEntity> entities = customerService.selectByMap(params);
        return R.ok().put("data",entities);
    }

    @GetMapping("/queryEntitiesList")
    public R queryEntitiesList(@RequestParam  String code){
        List<CustomerEntity> customerEntities = customerService.queryEntitiesList(code);
        return R.ok().put("data",customerEntities);
    }


    /**
     * 由地址ID获取客户关系
     */
    @GetMapping("/queryEntitiesListByAddressId/{addressId}")
    public R queryEntitiesListByAddressId(@PathVariable("addressId") Integer addressId){
        List<CustomerEntity> customerEntities = customerService.queryEntitiesListByAddressId(addressId);
        return R.ok().put("data",customerEntities);
    }







    @GetMapping("export")
    @RequiresPermissions("generator:customer:export")
    public void exportDate(@RequestParam Map<String, Object> params, HttpServletRequest request,
                           HttpServletResponse response) throws Exception {
        String[] lableNames = {"客户代码","中文名称","英文名称","客户属性","结算属性","所属项目","备注","预留字段1","预留字段2","预留字段3"};
        String[] columnNames={"code","cnName","enName","customerProperty","settlementProperty","projectName","remark","extendFirst","extendSecond","extendThird"};
        excelUtils.export(response,"数据导出.xlsx",lableNames,columnNames,params,customerExcelDataCreater);

    }

    /**
     * 客户导入
     */
    @PostMapping("/import")
    @CacheEvict(value = "customerController:queryEntity",allEntries=true)
    @RequiresPermissions("generator:customer:import")
    public R importFile(@RequestParam("file") MultipartFile file){

        Workbook book = ValidateFileTypeUtil.validate(file);
        if(book == null){
            return R.error();
        }
        try {
            return customerService.importFile(book);
        }catch (DuplicateKeyException d){
            return R.error(d.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }


}
